package com.sxfq.loansupermarket.backsystem.modular.theTest.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.constant.tips.Tip;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.util.CommUtils;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.analysis.entity.PlatFormCount;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.theTest.entity.SearchTestQuestionsInfo;
import com.sxfq.loansupermarket.backsystem.modular.theTest.entity.TestQuestionsInfo;
import com.sxfq.loansupermarket.backsystem.modular.theTest.service.ITestQuestionsService;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC;

@Controller
@SuppressWarnings("unused")
@RequestMapping("/testQuestions")
public class TestQuestionsController extends BaseController {

    private String PREFIX = "/theTest/";

    @Autowired
    private ITestQuestionsService Service;

    @Autowired
    private SqlMapper sqlMapper;

    /**
     * 跳转到订单信息
     */
    @RequestMapping("")
    public String testQuestionsIndex() {
        return PREFIX + "testQuestions.html";
    }

    /**
     * 跳转到修改考题
     */
//    @Permission
    @RequestMapping(value = "/testQuestions_edit/{testQuestionsInfoId}")
    public String to_edit(@PathVariable String testQuestionsInfoId, Model model) {
        if (ToolUtil.isEmpty(testQuestionsInfoId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        TestQuestionsInfo testQuestionsInfo = this.Service.selectOneById(testQuestionsInfoId);
        model.addAttribute("testQuestionsInfo", testQuestionsInfo);
        return PREFIX + "testQuestions_edit.html";
    }

    /**
     * 添加考题
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public int add(@Valid TestQuestionsInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        return Service.insert(info);
    }

    /**
     * 修改考题
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public int update(@Valid TestQuestionsInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        return Service.update(info);
    }

    /**
     * 删除考题
     */
    @RequestMapping(value = "/delete/{id}")
    @ResponseBody
    public Tip delete(@PathVariable String id) throws Exception {
        Service.delete(id);
        return SUCCESS_TIP;
    }

    /**
     * 跳转到添加考题
     */
//    @Permission
    @RequestMapping(value = "/testQuestions_add")
    public String to_add(Model model) {
        return PREFIX + "testQuestions_add.html";
    }

    /**
     * 导入试题
     */
    @RequestMapping(value = "/upload")
    public String importTestQuestions(@Valid MultipartFile file) {
        if (!StringUtil.isEmpty(file)) {
            Random random = new Random();
            String realPath = "D:\\yiyatmp\\" + random.nextInt(100);
            String FileInput = realPath + "\\" + file.getOriginalFilename();
            try {
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, file.getOriginalFilename()));
                InputStream is = new FileInputStream(FileInput);
                HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
                // 循环工作表Sheet
                Sheet hssfSheet = hssfWorkbook.getSheetAt(0);
                Row hssfRow0 = hssfSheet.getRow(0);
//                String sql = "insert into test_questions_info " +
//                        "( id, " + hssfRow0.getCell(0) + "," + hssfRow0.getCell(1) + "," + hssfRow0.getCell(2) + "" +
//                        "," + hssfRow0.getCell(3) + "," + hssfRow0.getCell(4) + "," + hssfRow0.getCell(5) + "" +
//                        "," + hssfRow0.getCell(6) + "," + hssfRow0.getCell(7) + "," + hssfRow0.getCell(8) + ",update_people,create_people,create_time,update_time) VALUES ";
                // 循环行Row ," + hssfRow0.getCell(8) + "
                for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    Row hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow == null) {
                        continue;
                    }
                    Cell xh1 = hssfRow.getCell(0);
                    Cell xh2 = hssfRow.getCell(1);
                    Cell xh3 = hssfRow.getCell(2);
                    Cell xh4 = hssfRow.getCell(3);
                    Cell xh5 = hssfRow.getCell(4);
                    Cell xh6 = hssfRow.getCell(5);
                    Cell xh7 = hssfRow.getCell(6);
                    Cell xh8 = hssfRow.getCell(7);
                    Cell xh9 = hssfRow.getCell(8);
                    String xh1s = ""; String xh2s = ""; String xh3s = ""; String xh4s = ""; String xh5s = "";
                    String xh6s = ""; String xh7s = ""; String xh8s = "";
                    if (!StringUtil.isEmpty(xh1)) {
                        xh1s = xh1.toString().trim();
                    }
                    if (!StringUtil.isEmpty(xh2)) {
                        xh2s = xh2.toString().trim();
                    }
                    if (!StringUtil.isEmpty(xh3)) {
                        xh3s = xh3.toString().trim();
                    }
                    if (!StringUtil.isEmpty(xh4)) {
                        xh4s = xh4.toString().trim();
                    }
                    if (!StringUtil.isEmpty(xh5)) {
                        xh5s = xh5.toString().trim();
                    }
                    if (!StringUtil.isEmpty(xh6)) {
                        xh6s = xh6.toString().trim();
                    }
                    if (!StringUtil.isEmpty(xh7)) {
                        xh7s = xh7.toString().trim();
                    }
                    if (!StringUtil.isEmpty(xh8)) {
                        xh8s = xh8.toString().trim();
                    }
                    if (StringUtil.isEmpty(xh1)) {
                        break;
                    }
//                    if (rowNum != hssfSheet.getLastRowNum()-1) {
//                        sql += "('" + CommUtils.getUUID() + "','" + xh1.toString().trim() + "','" + xh2.toString().trim() + "','" + xh3.toString().trim() + "'" +
//                                ",'" + xh4.toString().trim() + "','" + xh5.toString().trim() + "','" + xh6.toString().trim() + "'" +
//                                ",'" + xh7.toString().trim() + "','" + xh8s.toString().trim() + "','" + xh9.toString().trim() + "','" + ShiroKit.getUser().getName() + "','" + ShiroKit.getUser().getName() + "','" + DateTimeKit.now() + "'" +
//                                ",'" + DateTimeKit.now() + "'),";
//                    } else {
                    String  sql  = "insert into test_questions_info " +
                                "( id, " + hssfRow0.getCell(0) + "," + hssfRow0.getCell(1) + "," + hssfRow0.getCell(2) + "" +
                                "," + hssfRow0.getCell(3) + "," + hssfRow0.getCell(4) + "," + hssfRow0.getCell(5) + "" +
                                "," + hssfRow0.getCell(6) + "," + hssfRow0.getCell(7) + "," + hssfRow0.getCell(8) + ",update_people,create_people,create_time,update_time) VALUES "
                    +"('" + CommUtils.getUUID() + "','" + xh1s + "','" + xh2s + "','" + xh3s + "'" +
                                ",'" + xh4s + "','" + xh5s + "','" + xh6s + "'" +
                                ",'" + xh7s + "','" + xh8s + "','" + xh9.toString().trim() + "','" + ShiroKit.getUser().getName() + "','" + ShiroKit.getUser().getName() + "','" + DateTimeKit.now() + "'" +
                                ",'" + DateTimeKit.now() + "');";
//                    }
                    sqlMapper.insert(sql);
                }
                String updateSql = " update test_questions_info set  options_a=if(options_a='null','',options_a),options_b=if(options_b='null','',options_b)\n" +
                        " ,options_c=if(options_c='null','',options_c),options_d=if(options_d='null','',options_d),options_e=if(options_e='null','',options_e)\n" +
                        " ,options_f=if(options_f='null','',options_f)";//,title_type=if(title_type='null','',title_type)

                sqlMapper.update(updateSql);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return PREFIX + "testClose.html";
        } else {
            return PREFIX + "testClose.html";
        }
    }

    /**
     * 跳转到上传考题
     */
//    @Permission
    @RequestMapping(value = "/testQuestions_import")
    public String to_import(Model model) {
        return PREFIX + "testQuestions_import.html";
    }

    /**
     * 跳转到考试列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object list(SearchTestQuestionsInfo searchTestQuestionsInfo, HttpServletRequest request) {
        Page<TestQuestionsInfo> page = new PageFactory<TestQuestionsInfo>().defaultPage();
        try {
            SearchTestQuestionsInfo searchInfo = createSearchEntity(request);
            List<TestQuestionsInfo> list = Service.selectPageListByQueryGetMap(page, searchInfo);
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    public SearchTestQuestionsInfo createSearchEntity(HttpServletRequest request) {
        SearchTestQuestionsInfo searchInfo = new SearchTestQuestionsInfo();
        String testTitle = request.getParameter("testTitle");
        String titleType = request.getParameter("titleType");
        if (!CommUtils.isNull(testTitle)) {
            searchInfo.setTestTitle(testTitle);
        }
        if (!CommUtils.isNull(titleType)) {
            searchInfo.setTitleType(titleType);
        }
        return searchInfo;
    }

    /**
     * 获取excel模板
     *
     * @param response
     */
    @RequestMapping(value = "/getTemplateExcel")
    public void getTemplateExcel(HttpServletResponse response) {

        try {
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("批量上传试题模板");

            for (int i = 0; i < 8; i++) {
                sheet.setColumnWidth(i, 16 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("test_title");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("options_a");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("options_b");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("options_c");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("options_d");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("options_e");
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue("options_f");
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue("correct_answer");
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue("title_type");
            cell.setCellStyle(style);
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "试题导入模板" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取试题列表集合
     *
     * @return
     */
    public List<TestQuestionsInfo> testQuestionsInfoList() {
        List<TestQuestionsInfo> list = Service.selectTestQuestionsInfo();
        return list;
    }

    /**
     * 导出excel表
     *
     * @param response
     */
    @RequestMapping(value = "/downloadExcel")
    public void downloadChannelStatisticExcel(HttpServletResponse response) {

        try {
            List<TestQuestionsInfo> list = testQuestionsInfoList();
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("考试题");

            for (int i = 0; i < 9; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("test_title");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("options_a");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("options_b");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("options_c");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("options_d");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("options_e");
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue("options_f");
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue("correct_answer");
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue("title_type");
            cell.setCellStyle(style);
            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                TestQuestionsInfo map = list.get(i);
                row = sheet.createRow(i + 1);
                String testTitle = map.getTestTitle();
                String optionsA = map.getOptionsA();
                String optionsB = map.getOptionsB();
                String optionsC = map.getOptionsC();
                String optionsD = map.getOptionsD();
                String optionsE = map.getOptionsE();
                String optionsF = map.getOptionsF();
                String correctAnswer = map.getCorrectAnswer();
                String titleType = map.getTitleType();
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= 8; j++) {
                    row.createCell(j).setCellStyle(style);
                }
                row.getCell(0).setCellValue(testTitle);
                row.getCell(1).setCellValue(optionsA);
                row.getCell(2).setCellValue(optionsB);
                row.getCell(3).setCellValue(optionsC);
                row.getCell(4).setCellValue(optionsD);
                row.getCell(5).setCellValue(optionsE);
                row.getCell(6).setCellValue(optionsF);
                row.getCell(7).setCellValue(correctAnswer);
                row.getCell(8).setCellValue(titleType);
            }
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
